#!/usr/bin/env python3
"""
调试模式启动脚本
用于在Cursor中进行单步调试
"""

import os
import sys
import logging
import json
from flask import Flask, request

# 添加项目目录到Python路径
sys.path.insert(0, os.path.dirname(__file__))

# 设置详细的调试日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
)

from web.app import create_app
from services.config_manager import ConfigManager

def debug_device_config_endpoint():
    """调试设备配置API端点"""
    app = Flask(__name__)
    
    @app.route('/debug/device-config', methods=['POST'])
    def debug_save_config():
        """调试保存设备配置"""
        print("🔍 接收到设备配置请求")
        
        # 获取请求数据
        config_data = request.get_json()
        print(f"📋 接收到的数据: {json.dumps(config_data, indent=2, ensure_ascii=False)}")
        
        # 验证配置
        config_manager = ConfigManager()
        
        if config_data:
            # 标准化数据格式
            normalized_config = normalize_config_data(config_data)
            print(f"📋 标准化后的数据: {json.dumps(normalized_config, indent=2, ensure_ascii=False)}")
            
            # 验证配置
            validation_errors = config_manager.validate_devices_config([normalized_config])
            
            if validation_errors:
                print(f"❌ 验证失败: {validation_errors}")
                return {
                    'success': False,
                    'error': '配置验证失败',
                    'details': validation_errors
                }, 400
            else:
                print("✅ 验证通过")
                return {
                    'success': True,
                    'message': '配置验证通过'
                }
        
        return {'success': False, 'error': '无效数据'}, 400
    
    return app

def normalize_config_data(config_data):
    """标准化配置数据格式"""
    normalized = config_data.copy()
    
    # 处理数据点
    if 'points' in normalized and normalized['points']:
        for point in normalized['points']:
            # 转换dataType为data_type
            if 'dataType' in point:
                point['data_type'] = point.pop('dataType')
            
            # 移除空字符串字段
            keys_to_check = ['node_id', 'topic', 'address']
            for key in keys_to_check:
                if key in point and point[key] == '':
                    print(f"⚠️  警告：数据点 '{point.get('name')}' 的字段 '{key}' 为空字符串，将被移除")
                    del point[key]
    
    return normalized

def run_debug_server():
    """运行调试服务器"""
    print("🚀 启动调试服务器...")
    print("📍 调试端点: http://localhost:5001/debug/device-config")
    print("💡 使用此端点测试设备配置验证逻辑")
    
    app = debug_device_config_endpoint()
    app.run(host='0.0.0.0', port=5001, debug=True)

if __name__ == "__main__":
    # 可以在这里设置断点进行调试
    print("🔧 设备配置调试工具")
    print("选择调试模式:")
    print("1. 运行调试服务器")
    print("2. 测试配置验证")
    
    choice = input("请选择 (1 或 2): ").strip()
    
    if choice == "1":
        run_debug_server()
    elif choice == "2":
        # 直接测试配置验证
        from services.config_manager import ConfigManager
        
        test_config = {
            "name": "1#混流泵",
            "type": "opcua",
            "enabled": True,
            "polling_interval": 1000,
            "config": {
                "endpoint": "opc.tcp://192.168.1.100:4840/server"
            },
            "points": [
                {
                    "name": "VD300",
                    "node_id": "",  # 空字符串！
                    "data_type": "float"
                }
            ]
        }
        
        print("🧪 测试配置验证...")
        config_manager = ConfigManager()
        errors = config_manager.validate_devices_config([test_config])
        
        if errors:
            print(f"❌ 验证失败: {errors}")
        else:
            print("✅ 验证通过")
    else:
        print("❌ 无效选择") 